//
//  LAGMarkPoint.m
//  MapGisBusiness
//
//  Created by 罗亮富 on 2018/12/23.
//  Copyright © 2018年 Roen. All rights reserved.
//

#import "LAGMarkPoint.h"
#import <FoundationUtilities/FoundationUtilities.h>


@implementation LAGMarkPoint
{
    NSMutableArray *_attachements;
}
@synthesize identifier = _identifier;
@synthesize attachements = _attachements;

+(nullable instancetype)markPointWithJsonAtPath:(NSString *)jsonPath {
    
    LAGMarkPoint *p = [[LAGMarkPoint alloc] init];
    p->_jsonFilePath = [jsonPath copy];
    [p modelSetWithJSON:[NSData dataWithContentsOfFile:jsonPath]];
    return p;
}

-(void)saveToFile {
    
    NSError *error;
    //首先把文件都移到当前目录下
    for(LAGPointFile *f in _attachements) {
        
        if(![[f.fileUrl absoluteString] hasPrefix:@"http"]) {
            
            NSString *path = [f.fileUrl path];
            if(![path hasPrefix:self.directory]) { //将文件夹移动过来
                
                [self createDirecoryIfNotExist];
                
                NSString *desPath =[self.directory stringByAppendingPathComponent:[path lastPathComponent]];
                NSURL *desUrl = [NSURL fileURLWithPath:desPath];
                
                [[NSFileManager defaultManager] moveItemAtURL:f.fileUrl toURL:desUrl error:&error];
                if(!error)
                    f.fileUrl = desUrl;
            }
        }
    }
    
    NSData *jsonData = [self modelToJSONData];
    [jsonData writeToFile:self.jsonFilePath atomically:YES];
}

-(void)createDirecoryIfNotExist {
    
    NSFileManager *fm = [NSFileManager defaultManager];
    NSDictionary *attributes = nil;//[NSDictionary dictionaryWithObject:NSFileProtectionNone  forKey:NSFileProtectionKey];
    NSError *error;
    if(![fm fileExistsAtPath:self.directory isDirectory:NULL])
    {
        [fm createDirectoryAtURL:[NSURL fileURLWithPath:self.directory] withIntermediateDirectories:YES attributes:attributes error:&error];
        NSAssert(!error, @"%s CREATE %@ failed %@",__PRETTY_FUNCTION__,self.directory,error);
    }
    else
    {
        [fm setAttributes:attributes ofItemAtPath:self.directory error:&error];
    }
}

-(NSString *)directory {
    return [self.jsonFilePath stringByDeletingLastPathComponent];
}

-(NSArray <LAGPointFile *>*)attachements {
    if(_attachements)
        return [NSArray arrayWithArray:_attachements];
    else
        return nil;
}


-(void)addAttachement:(LAGPointFile *)file {
    
    if([_attachements containsObject:file])
        return;
    if(!_attachements)
        _attachements = [NSMutableArray arrayWithCapacity:5];
    
    [_attachements addObject:file];
}

-(void)removeAttachement:(LAGPointFile *)file {
    
    if([_attachements containsObject:file]) {
        
        if(file.fileUrl.isFileURL)
            [[NSFileManager defaultManager] removeItemAtURL:file.fileUrl error:nil];
        
        [_attachements removeObject:file];
    }
}



// attachements 不自动处理
//+ (nullable NSDictionary<NSString *, id> *)modelContainerPropertyGenericClass {
//    return @{@"attachements":[LAGPointFile class]};
//}

+ (nullable NSArray<NSString *> *)modelPropertyBlacklist {
    
    NSArray *superBlk = nil;
    if([super respondsToSelector:@selector(modelPropertyBlacklist)])
        superBlk = [super modelPropertyBlacklist];
    NSMutableArray *m = [NSMutableArray arrayWithArray:superBlk];
    [m addObject:@"jsonFilePath"];
    [m addObject:@"attachements"];
    [m addObject:@"directory"];
    return m;
}

- (BOOL)modelCustomTransformFromDictionary:(NSDictionary *)dic {
    
    NSArray *attches = [dic objectForKey:@"attachements"];
    NSMutableArray *atFiles = [NSMutableArray arrayWithCapacity:10];
    for(NSDictionary *adic in attches) {
        LAGPointFile *f = [[LAGPointFile alloc] init];
        NSString *fPath = [adic objectForKey:@"path"];
        if(fPath)
            f.fileUrl = [NSURL fileURLWithPath:[self.directory stringByAppendingPathComponent:fPath]];
        else
            f.fileUrl = [adic objectForKey:@"url"];
        
        f.metaType = [adic objectForKey:@"metaType"];
        if(f.fileUrl)
            [atFiles addObject:f];
    }
    
    if(atFiles.count > 0)
        _attachements = atFiles;
    else
        _attachements = nil;
    
    return YES;
}
- (BOOL)modelCustomTransformToDictionary:(NSMutableDictionary *)dic{
    
    NSMutableArray *fileDics = [NSMutableArray arrayWithCapacity:self.attachements.count];
    for(LAGPointFile *f in self.attachements) {
        if(f.fileUrl) {
            
            NSMutableDictionary *mDic = [NSMutableDictionary dictionaryWithCapacity:2];
            if([[f.fileUrl absoluteString] hasPrefix:@"http"]) {
                [mDic setObject:f.fileUrl forKey:@"url"];
            }
            else {
                NSString *path = [f.fileUrl path];
                if([path hasPrefix:self.directory]) {
                    
                    [mDic setObject:[path substringFromIndex:self.directory.length] forKey:@"path"];
                }
                else {
                    [mDic setObject:path forKey:@"path"];
                }
            }
            
            if(f.metaType)
                [mDic setObject:f.metaType forKey:@"metaType"];
            
            [fileDics addObject:mDic];
        }
    }
    
    if(fileDics.count > 0)
        [dic setObject:fileDics forKey:@"attachements"];
    
    
    return YES;
}


@end
